// pages/personal/purchase/orderDetail/siteDelivery/siteDelivery.js
import { create, query } from '../../../../../utils/service.js'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    item: '',
    orderStatus: '',
    productList: [],
    productTotal: '',
    totalPrice: 0,
    payInfoList: '',
    payTypeTotal: '',
    payTotal: 0,
    message:'',
    files:[],
    photoList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const id = options.id
    const that = this
    that.setData({
      id: id
    })


    query({
      url: 'api/waste/purchase/read',
      params: { id },
      back: function (data) {
        let item = data.result
        that.setData({
          orderStatus: item.cargo_sort_data
        })
      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log(1)

  },
  onlook: function (e) {
    wx.navigateTo({
      url: "../orderView/orderView?id=" + this.options.id
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    const productList = app.globalData.productList
    const payInfoList = app.globalData.payInfoList
   

    let totalPrice = 0
    productList.length > 0 && productList.map(item => {
      console.log(item)
      const money = item.unit_price * item.net_weight
      const newNumber = parseFloat(totalPrice * 1 + money * 1)
      totalPrice = newNumber.toFixed(2)
    })

    const payNum = payInfoList.length

    let payTotal = 0
    payInfoList.length > 0 && payInfoList.map(payItem => {
      const money = payItem.price * 1
      payTotal = (payTotal * 1 + money * 1) .toFixed(2)
    })

    that.setData({
      productList: productList,
      productTotal: productList.length,
      totalPrice: totalPrice,
      payInfoList: payInfoList,
      payTotal: payTotal,
      payTypeTotal: payNum
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.navigateTo({
      url: '../orderDetail'
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const list = that.data.files.concat(res.tempFilePaths)
        let sessionId = wx.getStorageSync('sessionId');
        let header = { 'content-type': 'application/json', 'Cookie': 'PHPSESSID=' + sessionId }
        list.map((item, index) => {
          //上传图片
          const uploadTask =  wx.uploadFile({
            url: 'https://testadmin.lhdrr.com/api/ajax/upload',
            filePath: list[index],
            name: 'file',
            header: header,
            success: function (res) {
             
              var data = JSON.parse(res.data)
              const photoList = that.data.photoList
              photoList.push(data.result.url)
              const newPhotos = [...new Set(photoList)]
              console.log(newPhotos)
              that.setData({
                photoList: newPhotos
              })
              

              //do something
            }
            
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
          
            if (res.progress != 100){
              wx.showLoading({
                title: '上传中',
              })
            }else{
              wx.hideLoading()
            }

          })
        })
          
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onAddGoods: function () {
    const that = this
    const status = that.data.orderStatus
    wx.navigateTo({
      url: "../enterProductInfo/enterProductInfo?status=" + status
    })
    // wx.navigateTo({
    //   url: "../pickGoods/pickGoods?status=" + status
    // })
  },
  onAddPay: function () {
    const status = 'new'
    wx.navigateTo({
      url: "../addPay/addPay?status=" + status
    })
  },
  onSubmit: function () {
    console.log(33333)
    const that = this
    const id = that.data.id
    const productList = that.data.productList
    const payInfoList =  that.data.payInfoList 
    const photoList = that.data.photoList
    productList.map(item => {
      delete item.parentMaterialType
      
      if (item.isTouchMove){
        delete item.isTouchMove
      }
    })
    payInfoList.map(item => {
      if (item.isTouchMove) {
        delete item.isTouchMove
      }
    })

    let cargo_pick_images = photoList
    let cargo_info = productList
    let expense_info = payInfoList
    const cargo_pick_remark = that.data.message 
    const data = {
      id,
      cargo_pick_images,
      cargo_info,
      expense_info,
      cargo_pick_remark,
      is_draft: 0
    }
    console.log(data)
    if (cargo_info.length == 0) {
      wx.showToast({
        title: '请填写完整',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '是否确认提交',
      success: function (res) {
        if (res.confirm) {
          create({
            url: 'api/waste/purchase/pick_cargo',
            params: { ...data },
            back: function (data) {
              if (data.code === 200) {
                wx.navigateTo({
                  url: "../siteSuccess/siteSuccess?id="+that.options.id
                })
                console.log(111)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onBlur: function (e) {
    const that = this
    const value = e.detail.value
    that.setData({
      message: value
    })
  },
  //手指触摸动作开始 记录起点X坐标 --------删除货品
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.productList.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      productList: this.data.productList
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.productList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      productList: that.data.productList
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  del: function (e) {
    this.data.productList.splice(e.currentTarget.dataset.index, 1)
    console.log("this.data.productList")
    console.log(this.data.productList)
    let productList = this.data.productList
    let totalPrice = this.data.totalPrice
    let money = [],newNumber = 0
    for (let i = 0; i < productList.length;i++){
      money.push(productList[i].unit_price * productList[i].net_weight)
    }
    console.log(money)
    for(let j=0;j<money.length;j++){
      newNumber += money[j]
    }
    totalPrice = newNumber.toFixed(2)
    this.setData({
      productList: this.data.productList,
      productTotal: productList.length,
      totalPrice: totalPrice
    })
    app.globalData.productList = this.data.productList
  },
  //手指触摸动作开始 记录起点X坐标 --------删除货品
  touchstartPay: function (e) {
    //开始触摸时 重置所有删除
    this.data.payInfoList.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      payInfoList: this.data.payInfoList
    })
  },
  //滑动事件处理
  touchmovePay: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.payInfoList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      payInfoList: that.data.payInfoList
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件  
  delPay: function (e) {
    this.data.payInfoList.splice(e.currentTarget.dataset.index, 1)
    
  
    let payInfoList = this.data.payInfoList
    let payTotal = this.data.payTotal
    let money = [],newNumber=0
    for(let i = 0;i<payInfoList.length;i++){
      money.push(Number(payInfoList[i].price))
    }
    for(let j=0;j<money.length;j++){
      newNumber += money[j]
    }
    payTotal = newNumber.toFixed(2)
    console.log(payTotal)
  
    this.setData({
      payInfoList: this.data.payInfoList,
      payTotal: payTotal
    })
    app.globalData.payInfoList = this.data.payInfoList
  },
})